package com.idea.zd.sys.util;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.io.FileOutputStream;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class WordUtilPoi {

	public static void searchAndReplace(String srcPath, String destPath,
            Map<String, Object> map) {
        try {
            XWPFDocument document = new XWPFDocument(
                    POIXMLDocument.openPackage(srcPath));
            // 替换段落中的指定文字
            List<XWPFParagraph> itPara = document.getParagraphs();
            for (int s=0;s < itPara.size();s++) {
                XWPFParagraph paragraph = (XWPFParagraph) itPara.get(s);



                //String s = paragraph.getParagraphText();
                Set<String> set = map.keySet();
                Iterator<String> iterator = set.iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    List<XWPFRun> run=paragraph.getRuns();
                     for(int i=0;i<run.size();i++)
                     {
                      if(run.get(i).getText(run.get(i).getTextPosition())!=null && run.get(i).getText(run.get(i).getTextPosition()).equals(key))
                      {
                        /**参数0表示生成的文字是要从哪一个地方开始放置,设置文字从位置0开始
                         * 就可以把原来的文字全部替换掉了
                        * */
                          if(key.equals("table")){
                              for (int z = 0;z <2;z++){
                                  XmlCursor cursor = paragraph.getCTP().newCursor();

                                  XWPFTable table = document.insertNewTbl(cursor);

                                  //样式控制
                                  CTTbl ttbl = table.getCTTbl();
                                  CTTblPr tblPr = ttbl.getTblPr() == null ? ttbl.addNewTblPr() : ttbl.getTblPr();
                                  CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW();
                                  //每个表格宽度
                                  //tblWidth.setW(new BigInteger("7000"));
                                  tblWidth.setType(STTblWidth.DXA);
                                  CTJc cTJc = tblPr.addNewJc();
                                  //表格居中
                                  cTJc.setVal(STJc.Enum.forString("center"));
                                  CTTblBorders borders = tblPr.addNewTblBorders();
                                  CTBorder hBorder = borders.addNewInsideH();
                                  hBorder.setVal(STBorder.Enum.forString("single"));  // 线条类型
                                  hBorder.setSz(new BigInteger("1")); // 线条大小
                                  hBorder.setColor("000000"); // 设置颜色

                                  //表格创建
                                  XWPFTableRow tableRowTitle = table.getRow(0);

//                        XWPFTableCell c0 = tableRowTitle.getCell(0);
//                        XWPFRun r = c0.addParagraph().createRun();
//                        r.setFontSize(10);
//                        r.setText("一号点");
//                        //设置单元格大小
//                        c0.getCTTc().addNewTcPr().addNewTcW().setW(new BigInteger("5"));

                                  createCell(tableRowTitle,0,"一号点",3);
                                  createCell(tableRowTitle,1,"空域所属分区",7000);
                                  createCell(tableRowTitle,2,"",7000);
                                  createCell(tableRowTitle,3,"空域分区传真",7000);
                                  createCell(tableRowTitle,4,"",7000);
                                  createCell(tableRowTitle,5,"作业日期",7000);
                                  createCell(tableRowTitle,6,"",7000);

                                  XWPFTableRow createRow = table.createRow();
                                  createCell(createRow,1,"空域申报单位",7000);
                                  createCell(createRow,2,"",7000);
                                  createCell(createRow,3,"传真",7000);
                                  createCell(createRow,4,"",7000);
                                  createCell(createRow,5,"队伍名称",7000);
                                  createCell(createRow,6,"",7000);
                                  XWPFTableRow createRow1 = table.createRow();
                                  createCell(createRow1,1,"作业点编码号",7000);
                                  createCell(createRow1,2,"",7000);
                                  createCell(createRow1,3,"作业地点",7000);
                                  createCell(createRow1,4,"",7000);
                                  createCell(createRow1,5,"预计时间",7000);
                                  createCell(createRow1,6,"",7000);
                                  XWPFTableRow createRow2 = table.createRow();
                                  createCell(createRow2,1,"经度",7000);
                                  createCell(createRow2,2,"",7000);
                                  createCell(createRow2,3,"纬度",7000);
                                  createCell(createRow2,4,"",7000);
                                  createCell(createRow2,5,"海拔高度",7000);
                                  createCell(createRow2,6,"",7000);
                                  XWPFTableRow createRow3 = table.createRow();
                                  createCell(createRow3,1,"最大射击高度",7000);
                                  createCell(createRow3,2,"",7000);
                                  createCell(createRow3,3,"射击方位",7000);
                                  createCell(createRow3,4,"",7000);
                                  createCell(createRow3,5,"作业半径",7000);
                                  createCell(createRow3,6,"",7000);
                                  XWPFTableRow createRow4 = table.createRow();
                                  createCell(createRow4,1,"弹种",7000);
                                  createCell(createRow4,2,"",7000);
                                  createCell(createRow4,3,"发射指挥",7000);
                                  createCell(createRow4,4,"",7000);
                                  createCell(createRow4,5,"联系方式",7000);
                                  createCell(createRow4,6,"",7000);



                                  WordUtilPoi.mergeCellsVertically(table,0,0,5);
                                  run.get(i).setText("",0);
                              }
                          }else{
                              run.get(i).setText((String)map.get(key),0);
                          }
                      }
                     }
                }
            }

            // 替换表格中的指定文字
            Iterator<XWPFTable> itTable = document.getTablesIterator();
            while (itTable.hasNext()) {
                XWPFTable table = (XWPFTable) itTable.next();
                int rcount = table.getNumberOfRows();
                for (int i = 0; i < rcount; i++) {
                    XWPFTableRow row = table.getRow(i);
                    List<XWPFTableCell> cells = row.getTableCells();
                    for (XWPFTableCell cell : cells) {
                        for (Entry<String, Object> e : map.entrySet()) {
                            if (cell.getText().equals(e.getKey())) {
                                cell.removeParagraph(0);
                                cell.setText((String) e.getValue());
                            }
                        }
                    }
                }
            }


            FileOutputStream outStream = null;
            outStream = new FileOutputStream(destPath);
            document.write(outStream);
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  static void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
        for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
            XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
            if ( rowIndex == fromRow ) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * 创建表格元素
     * @param tableRow
     */
    public static void createCell(XWPFTableRow tableRow,int cellIndex,String text,int cellWidth){
        XWPFTableCell cell = tableRow.getCell(cellIndex);
        cell = cell== null?tableRow.createCell():cell;
        cell.removeParagraph(0);
        XWPFRun r = cell.addParagraph().createRun();
        r.setFontFamily("宋体");
        r.setFontSize(8);
        r.setText(text);
        //设置单元格大小

        cell.getCTTc().addNewTcPr().addNewTcW().setW(new BigInteger(String.valueOf(cellWidth)));

    }
}
